// app.js
import {isToken,login} from "./api/user.js";
App({
  onLaunch() {
    this.checkToken();
  },
  // 验证token
  async checkToken() {
    if(wx.getStorageSync('nickName')) {
      let {errCode} = await isToken();
      // console.log(errCode);
      if(errCode == 0) {
        this.globalData.verifyLogin = true
      }else{
        this.globalData.verifyLogin = false
        wx.clearStorageSync()
      }
    }else{
      this.globalData.verifyLogin = false
      wx.clearStorageSync()
    }

  },

  // 登录
  login() {
    let _this = this;
    return new Promise(function(resolve,reject){
      wx.getUserProfile({
        desc:'用于更好的交互体验',
        success:(res) => {
          let {userInfo} = res;
          // console.log(userInfo);
          wx.setStorageSync('avatarUrl', userInfo.avatarUrl);
          wx.setStorageSync('nickName', userInfo.nickName);
          wx.login({
            timeout: 1000,
            success:async (res)=>{
              let {code} = res;
              userInfo = {
                avatar:userInfo.avatarUrl,
                gender:userInfo.gender,
                nickName:userInfo.nickName
              }
              userInfo = JSON.stringify(userInfo);
              let {errCode,token} = await login(code,userInfo);
              if(errCode == 0) {
                wx.setStorageSync('token', token);
                _this.globalData.verifyLogin = true;
                resolve({errCode:0,message:'成功'});
              }
            }
          })
        },
        fail:(err)=>{
          resolve({errCode:401,message:'拒绝'})
        }

      })
    })
  },

  globalData: {
    verifyLogin:false
  }
})
